﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;
using Taste;

namespace ASTClass
{
    class FuncOrAssignAST : AST
    {
        public FuncOrAssignAST() : base() { name = "FuncOrAssign"; }
        public FuncOrAssignAST(AST parent) : base(parent) { name = "FuncOrAssign"; }

        public override AST Clone()
        {
            FuncOrAssignAST ast = new FuncOrAssignAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());

            return ast;
        }

        public override void CodeGen(Taste.SymbolTable st, Taste.CodeFileGen cfg)
        {
            if (operators[0].Equals(Operator.Assign))
            {
                cfg.AddComment("---- Assigment statement ----");
                children[1].CodeGen(st, cfg);
                IdentAST id0 = children[0] as IdentAST;
                Var myvar = st.findLocalVar(id0.Value);
                if (myvar != null)
                {
                    //local
                    cfg.AddCommand("lw", "$t1, 0($sp)");
                    cfg.AddCommand("sw", "$t1, " + 4 * myvar.index + "($fp)");
                    cfg.AddCommand("addiu", "$sp, $sp ,4");
                }
                else
                {
                    myvar = st.findGlobalVar(id0.Value);
                    if (myvar != null)
                    {
                        //global
                        IdentAST tval = myvar.variable as IdentAST;
                        cfg.AddCommand("lw", "$t1, 0($sp)");
                        cfg.AddCommand("sw", "$t1, " + tval.Value + "($0)");
                        cfg.AddCommand("addiu", "$sp, $sp, 4");
                    }
                    else
                    {
                        //error
                        Console.WriteLine("Error, variable " + id0.Value + " not found!");
                        throw new Exception();
                    }
                }

            }
            if (operators[0].Equals(Operator.Func))
            {
                if (ChildCount() > 0)
                {
                    IdentAST fname = children[0] as IdentAST;
                    cfg.AddCommand("jal", fname.Value);
                }
            }
        }


        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern

    }
}
